package com.example.travel.fragment;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.travel.Interface.Implements.UserInterfaceImpl;
import com.example.travel.Interface.UserInterface;
import com.example.travel.R;
import com.example.travel.bean.User;


public class UpdateContactFragment extends Fragment {
    EditText etUpdateUserName,etUpdatePhone;
    Button btUpdateUser,btUpdateCancel;
    int user_id;
    UserInterface ui;
    User user=null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.update_contact, container, false);
        init(view);
        //从另一个fragment获得user_id的值
        user_id=getArguments().getInt("user_id");
        //根据关键字user_id从表user_table重新取出要修改的联系人，并在修改界面上显示
        ui=new UserInterfaceImpl(getContext());
        user=ui.getUserById(user_id);
        if(user!=null){
            etUpdateUserName.setText(user.getUser_name());
            etUpdatePhone.setText(user.getPhone());
        }

        btUpdateUser.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                String name=etUpdateUserName.getText().toString().trim();
                String phone=etUpdatePhone.getText().toString().trim();
                if(name==null||name.equals("")||phone.equals("")||phone==null){
                    Toast.makeText(getContext(),"请输入商品名称!",Toast.LENGTH_SHORT).show();
                }else{
                    //把数据封装到user对象
                    User user=new User();
                    user.setPhone(phone);
                    user.setUser_name(name);
                    user.setImage_name("");
                    user.setUser_id(user_id);
                    //把user对象保存到user_table
                    ui=new UserInterfaceImpl(getContext());
                    ui.updateUser(user);
                    Toast.makeText(getContext(),"商品修改成功!",Toast.LENGTH_SHORT).show();
                    getFragmentManager().beginTransaction().replace(
                            R.id.flconent,new MyContactFragment()
                    ).commit();
                }
            }
        });

        return view;
    }
    public void init(View view){
        etUpdatePhone=(EditText)view.findViewById(R.id.et_updatePhone);
        etUpdateUserName=(EditText)view.findViewById(R.id.et_updateUserName);
        btUpdateCancel=(Button)view.findViewById(R.id.bt_updateCancel);
        btUpdateUser=(Button)view.findViewById(R.id.bt_updateUser);
    }

}
